//
//  MyInfoViewController.m
//  Teacher
//
//  Created by 李飞 on 15/10/27.
//  Copyright (c) 2015年 xueyinyue. All rights reserved.
//

#import "MyInfoViewController.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "HomeViewController.h"
#import "ChooseInstrumentViewController.h"
#import "UserBSGetUploadToken.h"
#import "UserBSGetUserInfo.h"
#import "QiniuSDK.h"
#import "UserBSModifyUserInfo.h"
#import "ApplicationContext.h"
#import "ApiConfig.h"
#import "User.h"


@interface MyInfoViewController ()

@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _chooseArray = [[NSMutableArray alloc]init];
    
    //设置头像圆角
    _headImageBtn.imageView.clipsToBounds = YES;
    _headImageBtn.imageView.layer.cornerRadius = 37;
    _sex = @"0";
    self.title = @"个人信息";
    
    if (!_isComeHome)
    {
        UserBSGetUserInfo *userBSGetUserInfo = [[UserBSGetUserInfo alloc] init];
        //     [self showProgressView];
        [self runService:userBSGetUserInfo andComplete:^(EACService *service) {
            //       [self hideProgressView];
        } andSuccess:^(EACService * service, id o) {
            UserBSGetUserInfoResult *userBSGetUserInfoResult = o;
            if (userBSGetUserInfoResult.isSuccess) {
                
                User* user = [ApplicationContext instance].currentUser;
                NSURL *url = [NSURL URLWithString:user.photoUrl];
                _qiniuUrl = user.photoUrl;
                
                for (NSDictionary* dc in user.instrument)
                {
                    [_chooseArray addObject:dc[@"id"]];
                    
                    if (!_instrument)
                    {
                        _instrument =dc[@"name"];
                        continue;
                    }
                    _instrument = [NSString stringWithFormat:@"%@,%@",_instrument,dc[@"name"]];
                }
                
                if (_instrument)
                {
                    [_chooseInstrumentBtn setTitle:_instrument forState:normal];
                }
                else
                {
                    [_chooseInstrumentBtn setTitle:@"请选择" forState:normal];
                }
                
              //  [_headImageBtn sd_setImageWithURL:url forState:UIControlStateNormal];
                
                _nameTF.text = user.userName;
                _teachAgeTF.text = user.schoolage;
                _oneIntroduceTF.text = user.introduce;
                if ([user.sex intValue] == 1)
                {
                    _manSelect = YES;
                    _womanSelect = NO;
                }
                else
                {
                    _manSelect = NO;
                    _womanSelect = YES;
                }
            }
            else
            {
                SHOW_ALERTVIEW(@"提示", userBSGetUserInfoResult.message, 10, self);
            }
        }];

        [self.navigationItem setHidesBackButton:YES];
        [self initNavegationBar];
    }
    else
    {
        User* user = [ApplicationContext instance].currentUser;
        NSURL *url = [NSURL URLWithString:user.photoUrl];
        _qiniuUrl = user.photoUrl;
        [_headImageBtn sd_setImageWithURL:url forState:UIControlStateNormal];
        _nameTF.text = user.userName;
        _teachAgeTF.text = user.schoolage;
        _oneIntroduceTF.text = user.introduce;
        if ([user.sex intValue] == 1)
        {
            _manSelect = YES;
            _womanSelect = NO;
        }
        else
        {
            _manSelect = NO;
            _womanSelect = YES;
        }
        
        for (NSDictionary* dc in user.instrument)
        {
            [_chooseArray addObject:dc[@"id"]];
            
            if (!_instrument)
            {
                _instrument =dc[@"name"];
                continue;
            }
            _instrument = [NSString stringWithFormat:@"%@,%@",_instrument,dc[@"name"]];
        }
        
        [_chooseInstrumentBtn setTitle:_instrument forState:normal];
        
        [self initNavegationBar];
    }
    
    if (_manSelect)
    {
        UIImage *image = [UIImage imageNamed:@"man_select"];
            _sex = @"1";
        [_manBtn setImage:image forState:UIControlStateNormal];
        
    }
    if (_womanSelect)
    {
        UIImage *image = [UIImage imageNamed:@"woman_select"];
        _sex = @"2";
        [_womanBtn setImage:image forState:UIControlStateNormal];
        
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 设置头像
- (IBAction)onHeadImageBtnClick:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"从相册选择",@"相机", nil];
    [actionSheet showInView:self.view];
}

#pragma mark - 选择乐器
- (IBAction)onChooseInstrumentBtnClick:(id)sender {
    ChooseInstrumentViewController *chooseInstrumentViewController = [[ChooseInstrumentViewController alloc] initWithNibName:@"ChooseInstrumentViewController" bundle:nil];
    
    chooseInstrumentViewController.chooseArray = _chooseArray;
    
    NSLog(@"个人中心界面_chooseArray %@", _chooseArray );
    
    chooseInstrumentViewController.blockOfSetInstrument = ^(NSString *instrumentId,NSString *instrumentNames){
        _instrument = instrumentId;
        [_chooseInstrumentBtn setTitle:instrumentNames forState:normal];
    };
    [self presentViewController:chooseInstrumentViewController animated:YES completion:^{  }];
    
    
}

#pragma mark - 完成
- (IBAction)onOkClick:(id)sender {
    
    UserBSModifyUserInfo *userBSModifyUserInfo = [[UserBSModifyUserInfo alloc] init];
    
    NSLog(@"！！！！！！！！！！！！%@:",_qiniuUrl);
    userBSModifyUserInfo.photoUrl = _qiniuUrl;
    userBSModifyUserInfo.userName = _nameTF.text;
    
    userBSModifyUserInfo.sex = _sex;
    userBSModifyUserInfo.schoolage = _teachAgeTF.text;
    
    userBSModifyUserInfo.instrument = _instrument;
    
    userBSModifyUserInfo.introduce = _oneIntroduceTF.text;
    
        [self showProgressView];
    
    [self runService:userBSModifyUserInfo andComplete:^(EACService *service) {
         [self hideProgressView];
    } andSuccess:^(EACService * service, id o) {
        UserBSModifyUserInfoResult *userBSModifyUserInfoResult = o;
        if (userBSModifyUserInfoResult.isSuccess)
        {
            SHOW_ALERTVIEW(@"提示",userBSModifyUserInfoResult.message, 10, self);
        }
        else
        {
            SHOW_ALERTVIEW(@"提示",userBSModifyUserInfoResult.message, 1, self);
        }
    }];

}

- (IBAction)onManClick:(id)sender {
    _manSelect =! _manSelect;
    UIImage *image;
    if (_manSelect)
    {
        image = [UIImage imageNamed:@"man_select"];
        _sex = @"1";
    }
    else
    {
        image = [UIImage imageNamed:@"man"];
        _sex = @"0";
    }
    [_manBtn setImage:image forState:UIControlStateNormal];
    
    
    _womanSelect = NO;
    image = [UIImage imageNamed:@"woman"];
    [_womanBtn setImage:image forState:UIControlStateNormal];
    
}

- (IBAction)onWomanClick:(id)sender {   
    _womanSelect =! _womanSelect;
    UIImage *image;
    if (_womanSelect)
    {
        image = [UIImage imageNamed:@"woman_select"];
        _sex = @"2";
        
    }
    else
    {
        image = [UIImage imageNamed:@"woman"];
        _sex = @"0";
    }
    [_womanBtn setImage:image forState:UIControlStateNormal];
    
    _manSelect = NO;
    image = [UIImage imageNamed:@"man"];
    [_manBtn setImage:image forState:UIControlStateNormal];
}


#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *imgPickerController = [[UIImagePickerController alloc]init];
    
    //设置当拍照完或在相册选完照片后，是否跳到编辑模式进行图片剪裁。只有当showsCameraControls属性为true时才有效果
    imgPickerController.allowsEditing = YES;
    
    imgPickerController.delegate = self;
    //从上往下为0，1，2
    if (buttonIndex == 0)
    {
        //从相册选择
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            //      设置图片选择器的资源类型
            imgPickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        [self presentViewController:imgPickerController animated:YES completion:nil];
    }
    if (buttonIndex == 1)
    {
        //相机
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if (!isCamera) {
            NSLog(@"摄像头不可使用");
            SHOW_ALERTVIEW(@"摄像头不可使用,请检查设备！", nil, 0, self);
            return ;
        }
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            imgPickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
            imgPickerController.showsCameraControls = YES;
            //设置使用后置摄像头，可以使用前置摄像头
            imgPickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            //设置闪光灯模式
            imgPickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
            //设置相机支持的类型，拍照或录像
            imgPickerController.mediaTypes = @[(NSString*)kUTTypeImage];
        }
        [self presentViewController:imgPickerController animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    //如果返回的type等于kUTTypeImage，代表返回的是照片
    if ([type isEqualToString:(NSString*)kUTTypeImage])
    {
        //获取图片裁剪的图
        UIImage* edit = [info objectForKey:UIImagePickerControllerEditedImage];
        //判断当前相机使用的sourcetype是拍照还是相册
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        {
            //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
            UIImageWriteToSavedPhotosAlbum(edit, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
        
        if (_isComeHome)
        {
            self.blockOfSetImage(edit);
        }
        
        [_headImageBtn setImage:edit forState:UIControlStateNormal];
        
        
        NSData *data = UIImageJPEGRepresentation(edit, 0.1);
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.jpg"];
        
        if ([fileManager fileExistsAtPath:filePath]){
            
            NSLog(@"Photo size: %f",[[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]/(1024.0*1024.0));
        }
        
               
        //获取Token&Key;
        UserBSGetUploadToken *userBSGetUploadVideoToken = [[UserBSGetUploadToken alloc] init];
        userBSGetUploadVideoToken.type = @"1";
        [self showProgressView];
        [self runService:userBSGetUploadVideoToken
             andComplete:^(EACService *service) {
                 [self hideProgressView];
             }
              andSuccess:^(EACService *service, id o) {
                  UserBSGetUploadTokenResult *userBSGetUploadTokenResult = o;
                  
                  NSLog(@"***token:%@？？？？？？？？？？？？",userBSGetUploadTokenResult.token);
                  //七牛上传
                  QNUploadManager *uploadManager = [[QNUploadManager alloc] init];
                  QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil
                                                                progressHandler:^(NSString *key, float percent) {
                                                                    NSLog(@"Photo upload: %f",percent);
                                                                }
                                                                         params:nil
                                                                       checkCrc:NO
                                                             cancellationSignal:nil];
                  
                  [uploadManager putFile:filePath
                                     key:nil
                                   token:userBSGetUploadTokenResult.token
                                complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                                    NSLog(@"%@",resp);
                                    _qiniuUrl = resp[@"url"];
                                    NSLog(@"******_qiniuUrl:%@***********",_qiniuUrl);
                                }
                                  option:option];
              }];

    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//点击Cancel会自动响应此方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
    NSLog(@"saved..");
}


#pragma mark -  NavegationBar
- (void)initNavegationBar
{
    UIBarButtonItem *backBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonClick:)];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(onOkClick:)];
    if (!_isComeHome)
    {
        self.navigationItem.rightBarButtonItem = rightBtn;
    }
    else
    {
        self.navigationItem.leftBarButtonItem = backBarBtn;
        self.navigationItem.rightBarButtonItem = rightBtn;
    }
}


- (void)onBackButtonClick:(id)sender
{
    HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    [self.navigationController pushViewController:homeViewController animated:YES];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (alertView.tag == 10)
    {
        if (buttonIndex == 0)
        {
            HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
            [self.navigationController pushViewController:homeViewController animated:YES];
        }
    }
}
@end
